package com.elitel.frame.base.component.exportprojectdata;

import com.elitel.common.mongodb.MongoDBUtil;
import com.elitel.frame.main.entity.CfgDb;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description 获取框架库数据库类型
 * @author guoyanfei
 * @date 2017/12/28
 */
@Component("dataBaseConnInfo")
public class DataBaseConnInfo {
  @Value("${spring.db.dbType}")
  public String dataBaseType;

  /**
   * 测试数据库连接是否正常
   *
   * @param cfgdb
   * @return boolean
   */
  public static boolean testConnection(CfgDb cfgdb) {
    java.sql.Connection conn = null;
    boolean bConnect = false;

    String url = cfgdb.getDbUrl(); // "jdbc:oracle:thin:@localhost:1521:orcl";
    String user = cfgdb.getDbUser();
    String password = cfgdb.getDbPwd();

    try {
      switch (cfgdb.getDbVersion()) {
        case "MongoDB":
          try {
            MongoDBUtil.getInstance().createConnection(cfgdb.getDbUrl());
            bConnect = true;
          } catch (Exception ex) {
            ex.printStackTrace();
            bConnect = false;
          }
          break;
        default:
          Class.forName(cfgdb.getDbDrivername());
          try {
            // 建立连接
            conn = java.sql.DriverManager.getConnection(url, user, password);
            System.out.println("测试连接正常，连接结果：" + conn); // 用于在控制台输出返回的信息
            bConnect = true;
          } catch (Exception e) {
            e.printStackTrace();
            bConnect = false;
          }
          break;
      }

    } catch (ClassNotFoundException e) {
      System.out.println("测试连接异常：" + e.getMessage());
      e.printStackTrace();
      bConnect = false;
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception e) {
          System.out.println("测试连接异常：" + e.getMessage());
          bConnect = false;
          e.printStackTrace();
        }
      }
    }
    return bConnect;
  }
}
